/* (c)2010-2012 Andrea Caltroni (andrea.caltroni@pd.infn.it), INFN (www.infn.it)
 *
 * This file is part of the IGI Survey Portlet (from here on shortened to IGISP).
 * IGISP is free software: you can redistribute it and/or modify it 
 * under the terms of the GNU General Public License as published by the Free 
 * Software Foundation, either version 3 of the License, or (at your option) any 
 * later version.
 *
 * IGISP is distributed in the hope that it will be useful, but WITHOUT ANY 
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with IGISP. If not, see <http://www.gnu.org/licenses/>.
 */
package it.infn.grid.liferay.survey.modules.admin.controller;

import it.infn.grid.liferay.survey.modules.admin.web.ChangeAnswerOrderCommand;
import it.infn.grid.liferay.survey.modules.admin.web.ChangeAnswerOrderValidator;
import it.infn.grid.liferay.survey.modules.admin.web.QuestionPropertyEditor;
import it.infn.grid.liferay.survey.modules.admin.web.AnswerModePropertyEditor;

import java.util.ArrayList;
import java.util.List;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;

import org.ajm.spring.survey.modules.admin.model.Answer;
import org.ajm.spring.survey.modules.admin.model.AnswerMode;
import org.ajm.spring.survey.modules.admin.model.Question;
import org.ajm.spring.survey.modules.admin.service.AnswerService;
import org.ajm.spring.survey.modules.admin.service.QuestionService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.portlet.bind.PortletRequestDataBinder;
import org.springframework.web.portlet.bind.annotation.ActionMapping;
import org.springframework.web.portlet.bind.annotation.RenderMapping;

/**
 * The controller for the change answer order operation on the list of Answers
 * of a Survey.
 *
 * @author Andrea Caltroni, andrea.caltroni@pd.infn.it, INFN
 */
@RequestMapping(value="VIEW")
@Controller(value="changeAnswerOrderController")
public class ChangeAnswerOrderController {

    // ------------------------------------------------------------------------|
    // --- CONSTANTS ----------------------------------------------------------|
    // ------------------------------------------------------------------------|

    // --- CLASS VARIABLES ----------------------------------------------------|
    // ------------------------------------------------------------------------|
    // ------------------------------------------------------------------------|

    static Logger logger = Logger.getLogger(ChangeAnswerOrderController.class);

    // ------------------------------------------------------------------------|
    // --- INSTANCE VARIABLES -------------------------------------------------|
    // ------------------------------------------------------------------------|

    @Autowired
    @Qualifier("answerService")
    private AnswerService answerService;

    @Autowired
    @Qualifier("questionService")
    private QuestionService questionService;

    @Autowired
    @Qualifier("changeAnswerOrderValidator")
    private ChangeAnswerOrderValidator changeAnswerOrderValidator;

    // ------------------------------------------------------------------------|
    // --- CONSTRUCTORS -------------------------------------------------------|
    // ------------------------------------------------------------------------|

    // ------------------------------------------------------------------------|
    // --- CLASS METHODS ------------------------------------------------------|
    // ------------------------------------------------------------------------|

    // ------------------------------------------------------------------------|
    // --- INSTANCE METHODS ---------------------------------------------------|
    // ------------------------------------------------------------------------|

    /**
     * Setup binder for adding/editing surveys.
     */
    @InitBinder("changeAnswerOrderCommand")
    protected void initBinder(PortletRequestDataBinder binder) {

        binder.registerCustomEditor(Question.class, new QuestionPropertyEditor(questionService));
        binder.registerCustomEditor(AnswerMode.class, new AnswerModePropertyEditor());
    }

    // ------------------------------------------------------------------------|

    @ModelAttribute("changeAnswerOrderCommand")
    public ChangeAnswerOrderCommand getCommandObject(@RequestParam("questionID") Long questionId) {

        Question question = getQuestionService().findById(questionId);
        ChangeAnswerOrderCommand command = new ChangeAnswerOrderCommand(getQuestionService().findAnswers(question));
        return command;
    }

    // ------------------------------------------------------------------------|

    /**
     * Edits the order of a question's answers. Render phase.
     *
     * @param questionId
     * @param model
     * @return The attribute in the model defining the action of changing the order
     * of a question's answers.
     */
    @RenderMapping(params="action=showChangeAnswerOrderForm")
    public String showChangeAnswerOrderForm(@RequestParam("questionID") Long questionId, Model model) {

        Question question = getQuestionService().findById(questionId);
        model.addAttribute("question", question);
        // find valid position range for answers (1 is the lower value)
        Answer highestPosAnswer = getQuestionService().findHighestPositionAnswer(question);
        List<Integer> answerPositions = new ArrayList<Integer>();
        for (int pos = 1; pos <= highestPosAnswer.getPosition(); pos++) {
            answerPositions.add(pos);
        }
        model.addAttribute("answerPositions", answerPositions);

        return "answerOrderChange";
    }

    // ------------------------------------------------------------------------|

    /**
     * Saves the edited order of the answers of a question after validating it.
     * Action phase.
     *
     * @param request
     * @param response
     * @param chAnsOrderCommand 
     * @param result
     * @param sessionStatus
     */
    @ActionMapping(params="action=changeAnswerOrder")
    public void submitchangeAnswerOrderForm(ActionRequest request, ActionResponse response,
            @ModelAttribute("changeAnswerOrderCommand") ChangeAnswerOrderCommand chAnsOrderCommand, BindingResult result, SessionStatus sessionStatus) {

        getChangeAnswerOrderValidator().validate(chAnsOrderCommand, result);

        if (!result.hasErrors()) {
            List<Answer> answersList = new ArrayList<Answer>();
            answersList.addAll(chAnsOrderCommand.getAnswers());
            for (Answer answer : chAnsOrderCommand.getAnswers()) {
                getAnswerService().save(answer);
            }

            response.setRenderParameter("action", "viewQuestionAnswers");
            response.setRenderParameter("questionID", chAnsOrderCommand.getAnswers().first().getQuestion().getId().toString());
        }
        else {
            if (logger.isDebugEnabled()) {
                for (ObjectError error: result.getAllErrors()) {
                    logger.debug("Change answer order form reported [" + error.toString() + "]");
                }
            }
            response.setRenderParameter("action", "showChangeAnswerOrderForm");
            response.setRenderParameter("questionID", chAnsOrderCommand.getAnswers().first().getQuestion().getId().toString());
        }
        
        // TODO not necessary
        //sessionStatus.setComplete();
    }

    // --- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --|
    // ---[  GETTERS AND SETTERS  ]--------------------------------------------|
    // --- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --|

    /**
     * @return
     */
    private AnswerService getAnswerService() {

        return this.answerService;
    }

    // ------------------------------------------------------------------------|

    /**
     * @return the questionService
     */
    public QuestionService getQuestionService() {

        return questionService;
    }

    // ------------------------------------------------------------------------|

    /**
     * @param questionService the questionService to set
     */
    public void setQuestionService(QuestionService questionService) {

        this.questionService = questionService;
    }

    // ------------------------------------------------------------------------|
    
    /**
     * @return the changeAnswerOrderValidator
     */
    public ChangeAnswerOrderValidator getChangeAnswerOrderValidator() {
        return changeAnswerOrderValidator;
    }

    // ------------------------------------------------------------------------|

}
